document.addEventListener('DOMContentLoaded', () => {
    // 初始购物清单数据
    let shoppingList = JSON.parse(localStorage.getItem('shoppingList')) || [
        { id: 1, name: '牛奶', member: 'member1', purchased: false, category: 'daily' },
        { id: 2, name: '面包', member: 'member2', purchased: true, category: 'daily' },
        { id: 3, name: '鸡蛋', member: 'member3', purchased: false, category: 'daily' }
    ];
    
    const itemsList = document.getElementById('itemsList');
    const newItemInput = document.getElementById('newItem');
    const addButton = document.getElementById('addButton');
    const memberSelect = document.getElementById('memberSelect');
    const teamMembers = document.querySelectorAll('.member');
    
    // 渲染购物清单
    function renderShoppingList(member = 'all', category = 'all') {
        itemsList.innerHTML = '';
        
        let filteredList = shoppingList;
        
        if (member !== 'all') {
            filteredList = filteredList.filter(item => item.member === member);
        }
        
        if (category !== 'all') {
            filteredList = filteredList.filter(item => item.category === category);
        }
        
        filteredList.forEach(item => {
            const itemElement = document.createElement('div');
            itemElement.className = `item ${item.purchased ? 'purchased' : ''}`;
            
            itemElement.innerHTML = `
                <div class="item-name">${item.name}</div>
                <div><span class="member-badge ${item.member}">${getMemberName(item.member)}</span></div>
                <div class="status ${item.purchased ? 'purchased' : 'pending'}" data-id="${item.id}">
                    ${item.purchased ? '已购买' : '待购买'}
                </div>
                <div>
                    <button class="delete-btn" data-id="${item.id}">删除</button>
                </div>
            `;
            
            itemsList.appendChild(itemElement);
        });
        
        // 添加事件监听
        document.querySelectorAll('.status').forEach(status => {
            status.addEventListener('click', togglePurchaseStatus);
        });
        
        document.querySelectorAll('.delete-btn').forEach(btn => {
            btn.addEventListener('click', deleteItem);
        });
    }
    
    // 获取成员名称
    function getMemberName(memberId) {
        const memberNames = {
            'member1': '成员A',
            'member2': '成员B',
            'member3': '成员C'
        };
        return memberNames[memberId] || memberId;
    }
    
    // 切换购买状态
    function togglePurchaseStatus(e) {
        const itemId = parseInt(e.target.dataset.id);
        const itemIndex = shoppingList.findIndex(item => item.id === itemId);
        
        if (itemIndex !== -1) {
            shoppingList[itemIndex].purchased = !shoppingList[itemIndex].purchased;
            saveToLocalStorage();
            renderShoppingList(document.querySelector('.member.active').dataset.member);
        }
    }
    
    // 删除物品
    function deleteItem(e) {
        const itemId = parseInt(e.target.dataset.id);
        shoppingList = shoppingList.filter(item => item.id !== itemId);
        saveToLocalStorage();
        renderShoppingList(document.querySelector('.member.active').dataset.member);
    }
    
    // 添加新物品
    addButton.addEventListener('click', () => {
        const itemName = newItemInput.value.trim();
        if (itemName) {
            const newItem = {
                id: Date.now(), // 使用时间戳作为唯一ID
                name: itemName,
                member: memberSelect.value,
                purchased: false
            };
            
            shoppingList.push(newItem);
            saveToLocalStorage();
            renderShoppingList(document.querySelector('.member.active').dataset.member);
            newItemInput.value = '';
        }
    });
    
    // 按Enter添加物品
    newItemInput.addEventListener('keypress', (e) => {
        if (e.key === 'Enter') {
            addButton.click();
        }
    });
    
    // 切换团队成员视图
    teamMembers.forEach(member => {
        member.addEventListener('click', () => {
            teamMembers.forEach(m => m.classList.remove('active'));
            member.classList.add('active');
            renderShoppingList(member.dataset.member);
        });
    });
    
    // 保存到LocalStorage
    function saveToLocalStorage() {
        localStorage.setItem('shoppingList', JSON.stringify(shoppingList));
    }
    
    // 分类筛选事件
    document.querySelectorAll('.filter').forEach(filter => {
        filter.addEventListener('click', () => {
            document.querySelectorAll('.filter').forEach(f => f.classList.remove('active'));
            filter.classList.add('active');
            const currentMember = document.querySelector('.member.active').dataset.member;
            renderShoppingList(currentMember, filter.dataset.category);
        });
    });

    // 添加物品时保存分类
    addButton.addEventListener('click', () => {
        const itemName = newItemInput.value.trim();
        if (itemName) {
            const newItem = {
                id: Date.now(),
                name: itemName,
                member: memberSelect.value,
                category: document.getElementById('categorySelect').value,
                purchased: false
            };
            
            shoppingList.push(newItem);
            saveToLocalStorage();
            const currentFilter = document.querySelector('.filter.active').dataset.category;
            renderShoppingList(document.querySelector('.member.active').dataset.member, currentFilter);
            newItemInput.value = '';
        }
    });

    // 初始渲染
    renderShoppingList('all', 'all');
});